<template>
  <div class="product-type-box">
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <template v-for="(item, index) in formList">
        <el-form-item
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-if="item.prop"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)"
          >
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
    </el-form>
    <div class="model-info" v-if="tableData.length > 0">
      <el-row class="title">
        <el-col :span="6">名称</el-col>
        <el-col :span="6">标识符</el-col>
        <el-col :span="6">数据类型</el-col>
        <el-col :span="6"></el-col>
      </el-row>
      <el-row v-for="(item, index) in tableData" :key="index" class="row-item">
        <el-col :span="6">{{ item.modelName }}</el-col>
        <el-col :span="6">{{ item.modelTag }}</el-col>
        <el-col :span="6">{{ item.fieldTypeName }}</el-col>
        <el-col :span="6">
          <el-button @click="modelDeleteHandler(item)" size="small" type="danger"
                     icon="el-icon-delete-solid"></el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'

export default {
  name: 'AddProductType',
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      formData: {
        label: '',
        value: '',
        remark: '',
        modelIds: []
      },
      modelOptions: [],
      tableData: [],
      formList: [
        {
          name: '产品编号',
          prop: 'productTypeCode',
          attrConfig: { placeholder: '请输入产品编号' }
        },
        {
          name: '产品类型',
          prop: 'productTypeName',
          attrConfig: { placeholder: '请输入产品类型' }
        },
        {
          name: '备注',
          prop: 'remark',
          attrConfig: { type: 'textarea', placeholder: '(不超过300字)' }
        },
        {
          name: '产品模型',
          prop: 'modelIds',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'physicalModel.queryListNoPage',
          attrConfig: {
            placeholder: '请选择产品模型',
            multiple: true,
            style: { width: '100%' },
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'modelName',
            codeProp: 'id'
          }
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        productTypeName: [
          { required: true, message: '请输入产品类型名称', trigger: 'blur' }
        ],
        modelIds: [
          { required: true, message: '请选择产品模型', trigger: 'blur' }
        ]
        // value: [{ required: true, message: '请输入值', trigger: 'blur' }]
      }
    }
  },
  watch: {
    popData: {
      async handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          if (e.prop === 'modelIds') {
            this.$set(this.formData, e.prop, data[e.prop]?.split(','))
          } else {
            this.$set(this.formData, e.prop, data[e.prop])
          }
        })
        if (this.formData.modelIds?.length > 0) {
          this.tableData = await this.loadingDetailIds(this.formData.modelIds)
        }
        this.$set(this.formData, 'id', data.id)
        this.formList[0].attrConfig.disabled = !this.isAdd
        this.formList[1].attrConfig.disabled = !this.isAdd
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    async loadingDetailIds(ids) {
      const res = await this.$api.physicalModel.detailByIds(ids)
      return res.data
    },
    modelDeleteHandler(item) {
      this.formData.modelIds = this.formData.modelIds.filter(id => id !== item.id)
      this.tableData = this.tableData.filter(row => row.id !== item.id)
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
      if (config.prop === 'modelIds') {
        if (this.formData.modelIds.length === 0) {
          this.tableData = []
        } else {
          this.tableData = config.optionList.filter(item => this.formData.modelIds.includes(item.id))
          console.log(this.tableData)
        }
      }
    },
    /**
     * 提交
     */
    submit(params) {
      params.modelIds = params.modelIds.join(',')
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$api.productType[
            this.isAdd ? 'add' : 'update'
            ](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'product-type-add')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-textarea__inner {
  height: 140px !important;
}

.product-type-box {
  color: #333;
  padding: 0 20px;

  ::v-deep .el-form {
    // display: flex;
    // flex-wrap: wrap;
    // justify-content: space-between;

    .el-form-item {
      // width: calc(50% - 10px);

      &.width100p {
        width: 100%;
      }

      .el-form-item__label {
        color: #666;
        font-size: 14px;
      }

      &.form-sub-title {
        width: 100%;

        .el-form-item__label {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          font-weight: bold;
          color: #333;
          font-size: 16px;
          line-height: 1;

          &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 15px;
            background-color: #00858d;
            margin-right: 5px;
          }
        }
      }
    }

    .el-select,
    .el-cascader {
      width: 100%;
    }
  }
}

.model-info {
  margin-left: 115px;

  .title {
    line-height: 28px;
    font-size: 14px;
    font-weight: 600;
    display: flex;
    gap: 2px;
  }

  .row-item {
    line-height: 34px;
    display: flex;
    gap: 4px;
    margin-bottom: 10px;

    .el-col:not(:last-child) {
      background: #DCDFE6;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

}
</style>
